package loaders

import (
	"context"
	"path/filepath"
	"strings"
	"time"

	"github.com/nguyenthenguyen/docx"
)

// DocxLoader DOCX文件加载器
type DocxLoader struct {
	*BaseLoader
}

// NewDocxLoader 创建DOCX文件加载器
func NewDocxLoader(filePath string) *DocxLoader {
	return &DocxLoader{
		BaseLoader: NewBaseLoader(filePath),
	}
}

// Load 加载DOCX文件
func (l *DocxLoader) Load(ctx context.Context) ([]Document, error) {
	startTime := time.Now()
	l.logInfo("开始加载DOCX文件")

	// 打开DOCX文件
	doc, err := docx.ReadDocxFile(l.FilePath)
	if err != nil {
		l.logError(err, "打开DOCX文件失败")
		return nil, err
	}
	defer doc.Close()

	// 获取文档内容
	n := doc.Editable()
	content := n.GetContent()

	// 清理内容
	content = strings.TrimSpace(content)
	content = strings.ReplaceAll(content, "\r\n", "\n")
	content = strings.ReplaceAll(content, "\t", " ")

	// 提取段落
	paragraphs := make([]string, 0)
	for _, para := range strings.Split(content, "\n") {
		para = strings.TrimSpace(para)
		if para != "" {
			paragraphs = append(paragraphs, para)
		}
	}

	// 创建文档对象
	docObj := Document{
		Content: content,
		MetaData: map[string]interface{}{
			"file_path":       l.FilePath,
			"file_name":       filepath.Base(l.FilePath),
			"file_ext":        "docx",
			"content_type":    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
			"loader_type":     "DocxLoader",
			"load_time":       startTime.Format(time.RFC3339),
			"content_size":    len(content),
			"paragraph_count": len(paragraphs),
			"paragraphs":      paragraphs,
		},
		FilePath: l.FilePath,
	}

	l.logInfo("DOCX文件加载成功", map[string]interface{}{
		"paragraph_count": len(paragraphs),
		"content_size":    len(content),
		"load_time_ms":    time.Since(startTime).Milliseconds(),
	})

	return []Document{docObj}, nil
}
